package com.pkk.penguin.frame.know.java.Javacoreknowledge.threadlocal;

import java.util.concurrent.CountDownLatch;
import org.junit.Test;

/**
 * @description: 线程local的使用
 * @author: peikunkun
 * @create: 2020-01-13 14:45
 **/
public class ThreadLocalSimple {

  //静态类变量
  private final static ThreadLocal<String> local = new ThreadLocal();

  @Test
  @SuppressWarnings("all")
  public void Administrator_12_20200113151327() throws InterruptedException {
    System.out.println("欢迎使用单元测试方法【Administrator_12()_20200113151327】");
    System.out.println("此方法测试描述：【\n"
        + "1:每个线程中都有一个自己的 ThreadLocalMap 类对象，可以将线程自己的对象保持到其中,各管各的，线程可以正确的访问到自己的对象\n"
        + "2:ThreadLocalMap 其实就是线程里面的一个属性，它在 Thread 类中定义"
        + "3:将一个共用的 ThreadLocal 静态实例作为 key，将不同对象的引用保存到不同线程的ThreadLocalMap 中，然后在线程执行的各处通过这个静态 ThreadLocal 实例的 get()方法取\n"
        + "得自己线程保存的那个对象，避免了将这个对象作为参数传递的麻烦】");

    final Thread thread = Thread.currentThread();
    CountDownLatch countDownLatch = new CountDownLatch(2);
    System.out.println("######" + Thread.currentThread().getName() + "-" + local.get());
    local.set("测试");

    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("******" + Thread.currentThread().getName() + "-" + local.get());
        local.set("测试1");
        System.out.println("******" + Thread.currentThread().getName() + "-" + local.get());
        countDownLatch.countDown();
      }
    }).start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("$$$$$$" + Thread.currentThread().getName() + "-" + local.get());
        local.set("测试2");
        System.out.println("$$$$$$" + Thread.currentThread().getName() + "-" + local.get());
        countDownLatch.countDown();
      }
    }).start();

    countDownLatch.await();
    System.out.println("######" + Thread.currentThread().getName() + "-" + local.get());
  }

}
